﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bee.Util;
using Bee.Web;
using Bee.Data;
using System.Data;
using Bee.Models;
using org.in2bits.MyXls;
using Bee.Logging;

namespace Bee.Security.Controllers
{
    public class EmployeeController : AuthControllerBase<Employee>
    {
        static EmployeeController()
        {
            DataMapping.Instance.Register("EmployeeMapping", () =>
            {
                using (DbSession dbSession = new DbSession(ConfigUtil.GetAppSettingValue<string>(Constants.AuthDbConnectionKey)))
                {
                    return dbSession.ExecuteCommand(@"select a.*, b.username
from employee a left join authuser b on a.userid = b.id", null);
                }
            });
        }

        public override PageResult List(BeeDataAdapter dataAdapter)
        {
            // 由页面点击产生请求， 即页面初始
            if (!dataAdapter.ContainsKey("pagenum"))
            {
                dataAdapter["dimissionflag"] = false;
            }

            InitPagePara(dataAdapter);

            string name = dataAdapter.TryGetValue<string>("truename", string.Empty);
            dataAdapter.RemoveKey("truename");

            if (!dataAdapter.ContainsKey("username"))
            {
                dataAdapter.RemoveKey("userid");
            }

            if (!dataAdapter.ContainsKey("departmentname"))
            {
                dataAdapter.RemoveKey("departmentid");
            }

            SqlCriteria sqlCriteria = base.GetQueryCondition(dataAdapter);
            if (!string.IsNullOrEmpty(name))
            {
                sqlCriteria.And(SqlCriteria.New.StartWith("truename", name)
                    .Or(SqlCriteria.New.StartWith("namespell", name)));

                dataAdapter.Add("truename", name);
            }
            sqlCriteria.Equal("delflag", false);

            if (dataAdapter.ContainsKey("systemuser"))
            {
                sqlCriteria.GreaterThan("userid", 0);
            }

            DataTable dataTable = null;
            using (DbSession dbSession = GetDbSession())
            {
                string selectClause = GetQuerySelectClause(typeof(Employee));

                dataTable = base.InnerQuery("Employee", selectClause, dataAdapter, sqlCriteria);
            }


            return View(dataTable);
        }

        public PageResult Lookup(BeeDataAdapter dataAdapter)
        {
            DataTable orgData = DataMapping.Instance.GetMapping("AuthGroupMapping") as DataTable;
            orgData = DataUtil.Query(orgData, SqlCriteria.New.Equal("grouptype", 2));

            ViewData["orgData"] = orgData;


            return View(List(dataAdapter).Model);
        }

        public PageResult MultiLookup(BeeDataAdapter dataAdapter)
        {
            return View(this.Lookup(dataAdapter).Model);
        }

        public void Export(BeeDataAdapter dataAdapter)
        {
            dataAdapter["PageSize"] = int.MaxValue;
            DataTable result = List(dataAdapter).Model as DataTable;

            result = DataUtil.ForExport<Employee>(result);

            result.Columns.Remove("id");

            DataSet ds = new DataSet();
            ds.Tables.Add(result);

            XlsDocument xls = new XlsDocument(ds);

            xls.FileName = "雇员导出.xls";
            xls.Send();
            HttpContext.Current.Response.Flush();
        }

        public PageResult Upload()
        {
            return View();
        }

        public void Import(string url)
        {
            string path = HttpContextUtil.CurrentHttpContext.Server.MapPath(url);

            DataTable dataTable = DataUtil.LoadExcel(path);

            // 导入不能涉及用户名操作
            if (dataTable.Columns.Contains("用户名"))
            {
                dataTable.Columns.Remove("用户名");
            }
            if (dataTable != null)
            {
                DataTable importData = DataUtil.ForImport<Employee>(dataTable);

                int rowIndex = -1;
                foreach (DataRow row in importData.Rows)
                {
                    try
                    {
                        rowIndex++;
                        if (!string.IsNullOrEmpty(dataTable.Rows[rowIndex]["ImportResult"].ToString()))
                        {
                            continue;
                        }

                        using (DbSession dbSession = GetDbSession())
                        {
                            Employee employee = ConvertUtil.ConvertDataToObject<Employee>(row, null);

                            Employee dbEmployee = dbSession.Query<Employee>(SqlCriteria.New.Equal("workcode", employee.WorkCode)).FirstOrDefault();

                            if (dbEmployee != null)
                            {
                                if (string.Compare(dbEmployee.TrueName, employee.TrueName, false) != 0)
                                {
                                    dataTable.Rows[rowIndex]["ImportResult"] = "导入的姓名与库中的姓名不一致， 不允许修改姓名及工号";
                                    continue;
                                }
                            }

                            BeeDataAdapter data = BeeDataAdapter.From(dbEmployee);

                            BeeDataAdapter rowData = BeeDataAdapter.From(row);
                            rowData.RemoveEmptyOrNull();

                            data.Merge(rowData, true);

                            dbEmployee = ConvertUtil.ConvertDataToObject<Employee>(data);
                            dbEmployee.NameSpell = StringUtil.GetCapital(dbEmployee.TrueName);

                            dbSession.Save(dbEmployee);
                            

                            dataTable.Rows[rowIndex]["ImportResult"] = "导入成功";
                        }
                    }
                    catch (Exception e)
                    {
                        dataTable.Rows[rowIndex]["ImportResult"] = e.Message;
                        Logger.Error("导入失败!{0}".FormatWith(BeeDataAdapter.From(row)), e);
                    }
                }
            }

            DataSet ds = new DataSet();
            ds.Tables.Add(dataTable);

            XlsDocument xls = new XlsDocument(ds);

            xls.FileName = "雇员导入结果.xls";
            xls.Send();
            HttpContext.Current.Response.Flush();

            DataMapping.Instance.Refresh("EmployeeMapping");
        }

        public override void Save(Employee obj)
        {
            using (DbSession dbSession = GetDbSession())
            {
                bool workCodeValidFlag = false;
                bool nameValidFlag = false;
                if (obj.Id > 0)
                {
                    workCodeValidFlag =
                        dbSession.IsExist("Employee", SqlCriteria.New.Equal("workcode", obj.WorkCode).NotEqual("id", obj.Id));

                    nameValidFlag =
                        dbSession.IsExist("Employee", SqlCriteria.New.Equal("truename", obj.TrueName).NotEqual("id", obj.Id));
                }
                else
                {
                    workCodeValidFlag =
                        dbSession.IsExist("Employee", SqlCriteria.New.Equal("workcode", obj.WorkCode));

                    nameValidFlag =
                        dbSession.IsExist("Employee", SqlCriteria.New.Equal("truename", obj.TrueName));
                }

                ThrowExceptionUtil.ArgumentConditionTrue(!workCodeValidFlag, "WorkCode", "工号不能重复。");
                ThrowExceptionUtil.ArgumentConditionTrue(!nameValidFlag, "truename", "姓名不能重复。");

                obj.NameSpell = StringUtil.GetCapital(obj.TrueName);

            }

            base.Save(obj);

            DataMapping.Instance.Refresh("EmployeeMapping");
        }

        public override PageResult Show(int id)
        {
            PageResult result = base.Show(id);

            return View(result.Model);
        }

        public DataTable Suggest(string name)
        {
            SqlCriteria sqlCriteria = new SqlCriteria();

            sqlCriteria.Equal("delflag", false);

            if (!string.IsNullOrEmpty(name))
            {
                sqlCriteria.And(SqlCriteria.New.StartWith("truename", name)
                    .Or(SqlCriteria.New.StartWith("namespell", name)));
            }

            int dId = ViewData.TryGetValue<int>("did", -1);
            if (dId > 0)
            {
                DataTable authGroupData = DataMapping.Instance.GetMapping("AuthGroupMapping") as DataTable;
                List<int> groupList = authGroupData.GetChildren(dId);
                string groupString = string.Join(",", (from item in groupList select item.ToString()).ToArray());

                sqlCriteria.In("departmentid", groupString);
            }

            DataTable data = DataMapping.Instance.GetMapping("EmployeeMapping") as DataTable;

            return DataUtil.Suggest(data, "id,truename", sqlCriteria, 5);
        }

        public override void Delete(int id)
        {
            // 删除将删除与之关联的系统账号
            using (DbSession dbSession = GetDbSession(true))
            {
                Employee employee = dbSession.Query<Employee>(SqlCriteria.New.Equal("id", id)).FirstOrDefault();

                BeeDataAdapter data = new BeeDataAdapter();
                data.Add("delflag", 1);
                dbSession.Update("AuthUser", data, SqlCriteria.New.Equal("id", employee.UserId));
                dbSession.Update("Employee", data, SqlCriteria.New.Equal("id", id));
                dbSession.CommitTransaction();
            }
        }
    }

}
